<?php

namespace App\Http\Controllers\Api;

use App\Models\Bureau\WxBureau;
use App\Models\Bureau\WxBureauGroup;
use App\Models\Bureau\WxClubTeam;
use App\Models\Shop\WxShop;
use App\Models\Shop\WxShopContact;
use App\Models\Shop\WxShopFollow;
use App\Models\Shop\WxShopGuaranteeRecord;
use App\Models\Shop\WxShopOrder;
use App\Models\System\AdminUser;
use App\Models\Used\WxUsedGood;
use App\Models\WxIcon;
use App\Models\WxQuestion;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\ShopUtils;
use App\Wen\Utils\TaokeUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsGoods;
use App\Models\Shop\WxShopAddress;
use App\Models\Shop\WxShopCart;
use App\Models\Shop\WxShopClassify;
use App\Models\Shop\WxShopGoods;
use App\Models\Shop\WxShopGoodsProduct;
use App\Models\Shop\WxShopNotice;
use App\Models\Shop\WxShopService;
use App\Models\WxSlideshow;
use App\Models\User\WxUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class ShopController extends BaseController
{

    /**
     * Shop轮播图
     */
    public function bannerAndNav(Request $request)
    {
        global $__MINI_GLOBAL_DEVICE__;
        $ban_ids = ShopUtils::get_ban_classes($__MINI_GLOBAL_DEVICE__);
        $icon_id_arr = explode(',', Settings::get('app_shop_nav_', ''));
        $icons = [];
        WxIcon::whereIn('id', $icon_id_arr)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $icon_id_arr) . '"' . ")"))->get()->map(function ($v) use (&$icons, $ban_ids){
            if($v->type == 7 && in_array($v->target_id, $ban_ids)){

            }else{
                $icons[] = $v;
            }
        });

        $notice_ids = explode(',', Settings::get('app_shop_notice', ''));

        $result = [
            'banners' => WxSlideshow::wherein('id', explode(',', Settings::get('app_shop_banner', '')))->orderBy('sort', 'desc')->get(['id', 'poster', 'target_id', 'slideshow_type']),
            'navs' => $icons,
            'notice' => WxShopNotice::whereIn('id', $notice_ids)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $notice_ids) . '"' . ")"))->get(['id', 'title'])
        ];
        return  $this->success($result);
    }

    /**
     * Shop通知详情
     */
    public function noticeDetail(Request $request)
    {
        $id = $request->id;
        $data = WxShopNotice::where('id', $id)->first();
        return $this->success($data);
    }

    /**
     * Shop分类
     */
    public function classify(Request $request)
    {
        $device = $request->header('device','');
        $depth = _empty_default_($request->depth, 3);
        $hierarchy = _empty_default_($request->hierarchy, 0);
        $shop_id = _empty_default_($request->shop_id, 0);

        if($depth == 3){
            $depth_arr = [3, null];
        }else{
            $depth_arr = [$depth];
        }
        if($hierarchy == 1){
            $depth_arr = [1, 2, 3, null];
        }

        $ban_device_status = [0];
        if(is_mini_examine_mode(11)){
            $ban_device_status[] = 2;
        }


        if($hierarchy == 1){
            $query = WxShopClassify::whereNotIn('in_'.$device, $ban_device_status);
        }else{
            $query = WxShopClassify::where('state', 1)->whereNotIn('in_'.$device, $ban_device_status);
        }

        if($shop_id > 0){
            $shop_classifys = WxShop::where('id', $shop_id)->value('shop_classifys');
            if(_empty_($shop_classifys)){
                return $this->fail(200003);
            }
            $query = $query->whereIn('id', explode(',', $shop_classifys));
        }else if($shop_id == -1){

        }



        $data = $query->whereIn('depth', $depth_arr )->orderBy('sort', 'desc')
            ->get(FieldUtils::shopClassifyColums());

        if($hierarchy == 1){
            $firsts = [];
            $seconds = [];
            $thirds = [];

            if($data){
                $data = $data->toArray();
                foreach ($data as $v){
                    $v['sub'] = [];
                    if($v['depth'] == 1){
                        $firsts[$v['id']] = $v;
                    }else if($v['depth'] == 2){
                        $seconds[$v['id']] = $v;
                    }else{
                        $thirds[$v['id']] = $v;
                    }
                }

                if($thirds){
                    foreach ($thirds as $third_id => $third){
                        $parent_id = $third['parent_id'];
                        if($parent_id){
                            if(isset($seconds[$parent_id])){
                                $seconds[$parent_id]['sub'][] = $third;
                            }
                        }
                    }
                }
                if($seconds){
                    foreach ($seconds as $second_id => $second){
                        $parent_id = $second['parent_id'];
                        if($parent_id){
                            if(isset($firsts[$parent_id])){
                                $firsts[$parent_id]['sub'][] = $second;
                            }
                        }
                    }
                }
            }
            return $this->success(array_values($firsts));
        }else{
            return $this->success($data);
        }
    }

    /**
     * Shop首页板块推荐
     */
    public function plate(Request $request)
    {
        $data = WxShopClassify::where('state', 1)
            ->orderBy('sort', 'desc')->get(['id', 'name']);

        $data->map(function ($v) {
            $v->goods = WxShopGoods::where('state', 1)->where('classify_id', $v->id)
                ->orderBy('views', 'desc')->limit(3)
                ->get(['id', 'name', 'pic']);
        });

        return $this->success($data);
    }

    /**
     * Shop首页灵感推荐
     */
    public function inspiration(Request $request)
    {
        $data = WxShopGoods::where('state', 1)
            ->whereIn('id', explode(',', Settings::get('app_shop_accordion_goods', '')))
            ->limit(6)
            ->orderBy('sort', 'desc')
            ->get(['id', 'pic', 'tag', 'name', 'intro', 'vip_price']);
        return $this->success($data);
    }

    /**
     * Shop首页热榜推荐
     */
    public function hotList(Request $request)
    {

        $data = WxShopClassify::where('state', 1)->whereIn('id', Settings::get('app_shop_hot_list_classify', []))
            ->limit(6)->orderBy('sort', 'desc')->get(['id', 'name', 'intro', 'bg_img']);

        $data->map(function ($v) {
            $v->goods = WxShopGoods::where('state', 1)->where('classify_id', $v->id)
                ->limit(3)->orderBy('views', 'desc')
                ->get(['id', 'name', 'pic']);
        });

        return $this->success($data);
    }


    /**
     * Shop首页推荐
     */
    public function indexRecommend(Request $request)
    {
        global $__MINI_GLOBAL_DEVICE__;
        $ban_ids = ShopUtils::get_ban_classes($__MINI_GLOBAL_DEVICE__);
        $query = WxShopGoods::where('state', 1);
        if($ban_ids){
            $query = $query->whereNotIn('classify_id', $ban_ids);
        }

        $data = $query->orderBy('sort', 'desc')->orderBy('id', 'desc')
//            ->get(['id', 'pic', 'tag', 'name', 'intro', 'vip_price', 'price']);
            ->paginate(10);

        return $this->success($data);
    }



    /**
     * Shop商品详情
     */
    public function goodsDetails(Request $request)
    {
        global $__MINI_GLOBAL_MODE__;
        $id = $request->id;
        $uid = $request->uid;

        $dtk_id = $request->dtk_id;
        $tk_goodsid = $request->tk_goodsid;
        $tk_platform = $request->tk_platform;

        $force_update_id = false;

        if(_empty_($id)){
            $result = TaokeUtils::get_goods_id_from_taoke($dtk_id, $tk_goodsid, $tk_platform);
            if($result['code'] == 0){
                return $this->fail($result['data']);
            }
            $id = $result['data'];
            $force_update_id = true;
        }


        $device = $request->header('device','');
        if($device == 'pc'){
            $device = 'h5';
        }
        $ban_ids = ShopUtils::get_ban_classes($device);

        $data = WxShopGoods::where('id', $id)->whereNotIn('classify_id', $ban_ids)->with(['product'])->first();
        if($data){
            WxShopGoods::where('id', $id)->increment('views');
            if(_array_key($data, 'sku', '')){
                // 规格
                $attrs = json_decode($data['sku'], true);
                $data['param_data'] = $this->formatAttrs($attrs['attrs']);
            }else{
                $data['param_data'] = [];
            }


            // 服务
            if(isset($data['service_id'])){
                $data['service'] = WxShopService::whereIn('id', json_decode($data['service_id'], true))->get(['name', 'intro']);
            }else{
                $data['service'] = null;
            }

            // 处理时间
            $service_time_tip = '';
            if($data['service_time_start'] && $data['service_time_end']){
                $service_time_tip .= $data['service_time_start'].'-'.$data['service_time_end'];
            }
            if($data['service_date_start']){
                if($service_time_tip){
                    $service_time_tip = ' '.$service_time_tip;
                }
                if(_empty_($data['service_date_end'])){
                    if($service_time_tip){
                        $service_time_tip = $data['service_date_start'] . $service_time_tip;
                    }else{
                        $service_time_tip = $data['service_date_start'].'全天';
                    }

                }else{
                    $service_time_tip .= ($data['service_date_start'] . '-' . $data['service_date_end']) . $service_time_tip;
                }
            }else{
                if($service_time_tip){
                    if($service_time_tip){
                        $service_time_tip = ' '.$service_time_tip;
                    }
                    $service_time_tip = '每天' . $service_time_tip;
                }
            }
            $data['service_time_tip'] = $service_time_tip;

            // 处理嘉宾
            if($data['guest_present']){
                $data['guests'] = WxUser::whereIn('id', explode(',', $data['guest_present']))->orderBy(DB::raw('FIND_IN_SET(id, "' . $data['guest_present'] . '"' . ")"))->get(FieldUtils::userInfoColums())
                    ->map(function ($v){
                        $v->user_avatar = $v->user_avatar . '?imageMogr2/crop/50x50/gravity/center/thumbnail/50x50';
                        return $v;
                    });
            }

            if(_array_key($data, 'contact_id', 0) > 0){
                $data['contact'] = WxShopContact::find($data['contact_id']);
            }

            if($force_update_id){
                $data['force_update_id'] = true;
            }else{
                $data['force_update_id'] = false;
            }

            $data['user_purchase'] = ShopUtils::user_buy_goods_times($uid, $data->id);

            if($__MINI_GLOBAL_MODE__ != 'examine'){
                if($data->shop_id > 0){
                    $data->shop = WxShop::where('id', $data->shop_id )->first(FieldUtils::shopInfoColums());
                    ShopUtils::shop_process($data->shop);
                    if($data->shop->user_id != $data->user_id){
                        _logger_(__file__, __line__, '出错了，商品数据与店铺数据对应不上，商品id：'.$data->id . '，店铺id：'.$data->shop->id);
                    }
                }
            }




            if($uid > 0 && $id > 0){
                update_user_visit($uid, 3, $id);
            }

            return $this->success($data);
        }else{
            return $this->fail(200003, [], '无记录！');
        }
    }

    // 处理规格
    private function formatAttrs($attrs)
    {
        $data = [];
        foreach ($attrs as $k => $v) {
            foreach ($v as $ks => $vs) {
                $value[] = [
                    'value' => $vs
                ];
            }
            $data[] = [
                'name' => $k,
                'value' => $value
            ];
            $value = [];

        }
        return $data;
    }


    /**
     * Shop分类查询商品
     */
    public function classifyGoodsList(Request $request)
    {

        $cid = $request->cid;
        $device = $request->header('device','');
        $ban_ids = ShopUtils::get_ban_classes($device);
        if(in_array($cid, $ban_ids)){
            return $this->fail(200003, [], '无记录！');
        }

        if ($cid == -1) {
            $data = WxShopGoods::where('state', 1)
                ->orderBy('created_at', 'desc')
                ->paginate(6);
        } else if ($cid == 0) {
            $data = WxShopGoods::where('state', 1)
                ->orderBy('sort', 'desc')
                ->orderBy('views', 'desc')
                ->paginate(6);
        } else {
            $data = WxShopGoods::where('state', 1)->where('classify_id', $cid)
                ->orderBy('sort', 'desc')
                ->paginate(6);
        }

        return $this->success($data);
    }

    /**
     * Shop搜索商品
     */
    public function goodsSearch(Request $request)
    {
        $keyword = $request->keyword;
        $device = $request->header('device','');
        $ban_ids = ShopUtils::get_ban_classes($device);

        $shop_id = _empty_default_($request->shop_id, 0);

        $orderBy = _empty_default_($request->orderBy, 'sort');
        if(!in_array($orderBy, ['sort', 'buys', 'created_at', 'price'])){
            return $this->fail(200004);
        }
        $order = _empty_default_($request->order, 'desc');
        $limit = _between_(_empty_default_($request->limit, 10), 1, 100);

        $credit_type = $request->credit_type;
        if(_empty_($credit_type, true)){
            $credit_type = [0, 1];
        }
        if(is_string($credit_type)){
            $credit_type = explode(',', $credit_type);
        }
        foreach ($credit_type as $credit_type_){
            if(!in_array($credit_type_, [0, 1])){
                return $this->fail(200004);
            }
        }

        $minprice = _between_(_empty_default_($request->minPrice, 0), 0, 999999999);
        $maxPrice = _between_(_empty_default_($request->maxPrice, 999999999), 0, 999999999);
        if($minprice > $maxPrice){
            return $this->fail(200004);
        }
        $classify_id = _empty_default_($request->classify, 0);

        if(!in_array($order, ['desc', 'asc'])){
            return $this->fail(200004);
        }
        if($orderBy != 'price'){
            $order = 'desc';
        }


        $query = WxShopGoods::where('state', 1);

        $query = $query->where(function ($query_) use ($keyword) {
            $query_->orWhere('name', 'like', '%' . $keyword . '%')
                ->orWhere('intro', 'like', '%' . $keyword . '%')
                ->orWhere('content', 'like', '%' . $keyword . '%');
        });

        if($shop_id > 0){
            $query = $query->where('shop_id', $shop_id);
        }else if($shop_id == -1){
            $query = $query->where('shop_id', 0);
        }

        if($classify_id > 0){
            $query = $query->where('classify_id', $classify_id);
        }else{
            $query = $query->whereNotIn('classify_id', $ban_ids);
        }

        if($minprice > 0){
            $query = $query->where('price', '>=', $minprice);
        }
        if($maxPrice != 9999999999){
            $query = $query->where('price', '<=', $maxPrice);
        }

        $query = $query->whereIn('credit_type', $credit_type);

        $data = $query->orderBy($orderBy, $order)->orderBy('id', 'desc')->paginate($limit);

        return $this->success($data);
    }

    /**
     * Shop商品晒单
     */
    public function goodsPosts(Request $request)
    {
        $gid = $request->gid;
        $uid = $request->uid;

        $dtk_id = $request->dtk_id;
        $tk_goodsid = $request->tk_goodsid;
        $tk_platform = $request->tk_platform;

        if(_empty_($gid)){
            $result = TaokeUtils::get_goods_id_from_taoke($dtk_id, $tk_goodsid, $tk_platform);
            if($result['code'] == 0){
                return $this->fail($result['data']);
            }
            $gid = $result['data'];
        }

        $postsIds = WxPostsGoods::where('goods_id', $gid)->pluck('posts_id');//笔记ID列表

        $data = WxPost::where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('id', $postsIds)->orderBy('weight', 'desc')
            ->limit(5)->get();

        $results = [];
        if($data){
            $style  = 0;
            $data->map(function ($v) use ($style, &$results){
                $posts_content = strip_tags($v->posts_content);
                $obj = [
                    'id' => $v->id,
                    'content' => PostUtils::get_the_title($posts_content, $v->id),
                    'author' => WxUser::where('id', $v->user_id)->first(FieldUtils::userInfoColums()),
                    'imgs' => [

                    ],
                    'img_res' => 0
                ];
                $images = [];
                if($v->video){
                    $images[] = Utils::imgWithStyle($v->video->video_thumb_url, 2);
                }
                WxPostsImg::where('posts_id', $v->id)->get(['img_url', 'posts_id'])->map( function ($postImg) use ($style, &$images){
                    if($style == -1){
                        return $postImg;
                    }
                    $postImg->img_url = Utils::imgWithStyle($postImg->img_url, 2);
                    $images[] = $postImg->img_url;
                });//图片
                preg_replace_callback("/<img.*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", function ($r) use ($style, &$images){
                    $images[] = Utils::imgWithStyle($r[1], 2);
                    return '<img src="'.Utils::imgWithStyle($r[1], $style).'">';
                }, $v->posts_content);
                $obj['imgs'] = $images;
                $obj['img_res'] = count($images) > 3 ? (count($images) - 3) : 0;
                if($obj['img_res'] > 9){
                    $obj['img_res'] = 9;
                }
                $results[] = $obj;
            });
        }


        return $this->success($results);
    }
    /**
     * Shop商品晒单
     */
    public function goodsPostsList(Request $request)
    {
        $gid = $request->gid;
        $uid = $request->uid;

        $data = PostsRepositores::goodsBaskPosts($uid, $gid);

        return $this->success($data);
    }

    public function guarantee_record(Request $request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200015);
        }
        $shop_id = WxUser::where('id', $uid)->value('shop_id');
        if(_empty_($shop_id)){
            return $this->fail(200003);
        }
        $limit = _between_(_empty_default_($request->limit, 10), 1, 100);
        $data = WxShopGuaranteeRecord::where('shop_id', $shop_id)->orderBy('id', 'desc')->simplePaginate($limit);
        return $this->success($data);
    }

    /**
     * 店铺信息
     */
    public function info(Request $request){
        $user_id = $request->user_id;
        $shop_id = $request->shop_id;
        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        $is_admin = false;
        if(_empty_($user_id) && _empty_($shop_id)){
            return $this->fail(200001);
        }
        $shop_config = _empty_default_($request->shop_config, 0);
        $shop = null;
        if($user_id){
            $shop = WxShop::where('user_id', $user_id)->first(FieldUtils::shopInfoColums());
        }else{
            if($shop_id > 0){
                $shop = WxShop::where('id', $shop_id)->first(FieldUtils::shopInfoColums());
                ShopUtils::shop_process($shop);
            }else if($shop_id == -1){
                $shop = [
                    'id' => 0,
                    'shop_name' => '官方自营',
                    'shop_logo' => Settings::get('about_logo'),
                    'follow_count' => (WxShopFollow::where('shop_id', 0)->where('status', 1)->count()) ?: 0,
                    'is_follow' => WxShopFollow::where('user_id', $__MINI_GLOBAL_CURRENT_USER_ID__)->where('shop_id', 0)->where('status', 1)->exists(),
                    'status' => 1
                ];
                $is_admin = true;
            }
        }
        if(!$is_admin){
            if(_empty_($shop)){
                if($shop_config != 1){
                    return $this->fail(200003);
                }
            }
            if($shop){
                $shop->status_tip = [0=>'审核中', 1=>'审核通过',2=>'审核拒绝', 3=> '系统惩罚下线', 4 => '管理员惩罚下线', 5=> '店主关停'][$shop->status];
                if(!_empty_($shop->admin_user_id)){
                    $shop->admin_user = AdminUser::where('id', $shop->admin_user_id)->first(['id', 'username', 'name', 'avatar', 'uid', 'created_at']);
                    if($shop->admin_user){
                        $shop->admin_user['url_address'] = admin_url('');
                    }
                }
            }
        }

        if($shop){
            $shop->contacts = WxShopContact::where('shop_id', $shop->id)->get();
        }

        if($shop_config == 1){
            $object_ids = explode(',', Settings::get('app_shop_apply_questions', ''));
            $config = [
                'clause' => Settings::get('app_shop_apply_clause'),
                'questions' => WxQuestion::whereIn('id', $object_ids)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $object_ids) . '"' . ")"))->get()
            ];
            return $this->success(['shop'=>$shop, 'config'=>$config]);
        }

        return $this->success(['shop'=>$shop]);
    }

    /**
     * 关注店铺
     */
    public function follow(Request $request){
        $shop_id = _empty_default_($request->shop_id, 0);
        $status = _empty_default_($request->status, 0);
        $uid = $request->uid;

        if(_empty_($shop_id)){
            return $this->fail(200001);
        }
        if($shop_id == -1){
            $shop_id = 0;
        }

        if(!in_array($status, [0, 1])){
            return $this->fail(200004);
        }
        $model = WxShopFollow::where('user_id', $uid)->where('shop_id', $shop_id)->first();
        if($model){
            if($status == 1){
                if($model->status === 0){
                    $model->status = 1;
                    $model->save();
                }
            }else{
                if($model->status === 1){
                    $model->status = 0;
                    $model->save();
                }
            }
        }else{
            $new_model = new WxShopFollow();
            $new_model->user_id = $uid;
            $new_model->shop_id = $shop_id;
            $new_model->status = $status;
            $new_model->save();
        }
        return $this->success();
    }

    public function contact_process(Request $request){
        $action = _empty_default_($request->action , '');
        $uid = $request->uid;
        if($action == 'add'){
            $name = _empty_default_($request->name, '');
            $phone = _empty_default_($request->phone, '');
            $longitude = _empty_default_($request->longitude, 0);
            $latitude = _empty_default_($request->latitude, 0);
            $address_name = _empty_default_($request->address_name, '');
            $address_detailed = _empty_default_($request->address_detailed, '');

            if(_empty_($name) || _empty_($phone) || _empty_($longitude) || _empty_($latitude) || _empty_($address_name)){
                return $this->fail(200001);
            }

            $shop_id = WxShop::where('user_id', $uid)->value('id');
            if(_empty_($shop_id)){
                return $this->fail(200004, [], '你还没有申请店铺');
            }

            $contact = new WxShopContact();
            $contact->user_id = $uid;
            $contact->shop_id = $shop_id;
            $contact->name = $name;
            $contact->phone = $phone;
            $contact->longitude = $longitude;
            $contact->latitude = $latitude;
            $contact->address_name = $address_name;
            $contact->address_detail = $address_detailed;
            $r = $contact->save();
            if($r){
                return $this->success();
            }
            return $this->fail(200002);
        }else if($action == 'delete'){

        }
    }

    /**
     * Shop创建
     */
    public function add(Request $request){

        global $__MINI_GLOBAL_PAYCODE_31__;
        if(!$__MINI_GLOBAL_PAYCODE_31__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        $user = WxUser::find($uid);

        if(!UserUtils::is_user_can_speak($uid)){
            return $this->fail(200043, [
                'title' => '禁言中，无法言论',
                'content' => '是否前往解除限制',
                'confirmText' => '去解除',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$uid
            ], '您当前处于禁言期间，无法言论');
        }

        if(WxShop::withTrashed()->where('user_id', $uid)->exists()){
            return $this->fail(200010, [], '一个账号只能拥有一个店铺');
        }

        $shopClassifys = _empty_default_($request->shopClassifys, []);
        if(is_string($shopClassifys)){
            $shopClassifys = explode(',', $shopClassifys);
        }
        if(!is_array($shopClassifys)){
            return $this->fail(200001, [], '请选择类目后提交');
        }
        if(_empty_($shopClassifys)){
            return $this->fail(200001, [], '请选择类目后提交');
        }

        if(WxShopClassify::whereIn('id', $shopClassifys)->count() != count($shopClassifys)){
            return $this->fail(200004, [], '所提交的经营类目不合法，请尝试重新提交');
        }

        $margin_least = 0;
        WxShopClassify::whereIn('id', $shopClassifys)->get()->map(function ($v) use (&$margin_least){
            $margin_least += $v->guarantee;
        });

        // 这个只代表当时的一个状态
        $real_name = $user->real_name;
        $real_id_card = $user->real_id_card;
        if(_empty_($real_name)){
            return $this->fail(200001, [], '您还没有实名');
        }


        DB::beginTransaction();
        try {
            // todo:
            $model = new WxShop();
            $model->user_id = $uid;
            $model->shop_type = 1;
            $model->head_id_card_num = $real_id_card;
            $model->head_name = $real_name;

            $model->shop_classifys = implode(',', $shopClassifys);
            $model->margin_least = $margin_least;

            $model->status = 0;
            $r = $model->save();

            if($r){
                WxUser::where('id', $uid)->update(['shop_id' => $model->id]);
                Cache::forget('get:cached:user:'.$uid);
                DB::commit();
                return $this->success(['id'=>$model->id]);
            }else{
                DB::rollBack();
                return $this->fail(200002);
            }
        } catch (\Exception $e) {
            _logger_(__file__, __line__, $e->getMessage());
            DB::rollBack();
            return $this->fail(200002);
        }

    }


    /**
     * Shop添加购物袋
     */
    public function addCart(Request $request)
    {
        $num = $request->num;
        $uid = $request->uid;
        $pid = $request->pid;
        $goods_id = $request->gid;
        $action = $request->action;
        if(!in_array($action, ['buy', 'cart', 'gold', 'used', 'bureau'])){
            $action = 'cart';
        }
        _limit_user('add:cart', $uid, 30);

        if($action == 'used'){
            if(_empty_($goods_id)){
                return $this->fail(200001);
            }

            $used_good = WxUsedGood::find($goods_id);
            if(_empty_($used_good)){
                return $this->fail(200003);
            }
            if($used_good->status != 1){
                return $this->fail(200004, [], '该商品状态已不可购');
            }

            if($used_good->image_urls){
                $used_good->pic = _array_key($used_good->image_urls[0], 'url', '') . '';

                $used_good->pic_width = _array_key($used_good->image_urls[0], 'width', '');
                $used_good->pic_height = _array_key($used_good->image_urls[0], 'height', '');

                if($used_good->pic_width >= 350){
                    $old_widht = $used_good->pic_width;
                    $used_good->pic_width = 352;
                    $used_good->pic_height = (int)( (352 * $used_good->pic_width) / $old_widht );
                }

            }

            $model = new WxShopCart();
            $model->user_id = $uid;
            $model->seller_user_id = $used_good->user_id;
            $model->goods_id = $goods_id;
            $model->product_id = $pid;
            $model->goods_type = 6;
            $model->goods_pic = $used_good->pic;
            $model->goods_name = $used_good->title;
            $model->goods_product = '';
            $model->price = $used_good->price;
            $model->vip_price = $used_good->price;
            $model->credit_type = 1;
            $model->num = 1;
            $model->is_check = 1;
            $model->state = 6;
            $model->save();
            UserUtils::add_user_experience($uid, 10);
            return $this->success(['cart_id' => $model->id]);

        }else if($action == 'bureau'){
            if(_empty_($goods_id) || _empty_($pid)){
                return $this->fail(200001);
            }

            $bureau_good = WxBureau::find($goods_id);
            if(_empty_($bureau_good)){
                return $this->fail(200003);
            }
            if($bureau_good->status != 1){
                return $this->fail(200004, [], '该组局状态已不可购');
            }

            if($bureau_good->image_urls){
                $bureau_good->pic = _array_key($bureau_good->image_urls[0], 'url', '') . '';

                $bureau_good->pic_width = _array_key($bureau_good->image_urls[0], 'width', '');
                $bureau_good->pic_height = _array_key($bureau_good->image_urls[0], 'height', '');

                if($bureau_good->pic_width >= 350){
                    $old_widht = $bureau_good->pic_width;
                    $bureau_good->pic_width = 352;
                    $bureau_good->pic_height = (int)( (352 * $bureau_good->pic_width) / $old_widht );
                }
            }

            $team = WxClubTeam::find($pid);
            if(_empty_($team)){
                return $this->fail(200003);
            }

            $group = WxBureauGroup::find($team->group_id);
            if(_empty_($group)){
                return $this->fail(200003);
            }

            $price = $group->cost_per_person;
            if($group->type == 2){
                return $this->fail(200003, [], '暂不支持加入战队赛');
            }

            $model = new WxShopCart();
            $model->user_id = $uid;
            $model->seller_user_id = $bureau_good->user_id;
            $model->goods_id = $goods_id;
            $model->product_id = $team->id;
            $model->goods_type = 7;
            $model->goods_pic = $bureau_good->pic;
            $model->goods_name = $bureau_good->title;
            $model->goods_product = '';
            $model->price = $price;
            $model->vip_price = $price;
            $model->credit_type = 1;
            $model->num = 1;
            $model->is_check = 1;
            $model->state = 7;
            $model->save();
            UserUtils::add_user_experience($uid, 10);
            return $this->success(['cart_id' => $model->id]);

        } else{
            if(_empty_($num) || _empty_($goods_id) || _empty_($pid) || $num <= 0){
                return $this->fail(200001);
            }

            $shop_goods = WxShopGoods::find($goods_id);
            if(_empty_($shop_goods)){
                return $this->fail(200003);
            }

            $can_purchase_times = $shop_goods->can_purchase_times;
            if($can_purchase_times != 0){
                if(ShopUtils::user_buy_goods_times($uid, $goods_id) >= $can_purchase_times){
                    return $this->fail(800004);
                }
            }

            $WxShopGoodsProduct = WxShopGoodsProduct::find($pid);
            $pstock = $WxShopGoodsProduct->stock;

            if ($pstock > 0) {
                if($action == 'cart'){
                    if($shop_goods->type == 5){
                        return $this->fail(200001, [], '核销类型商品不能加入购物车');
                    }
                    $isExists = WxShopCart::where('user_id', $uid)->where('product_id', $pid)->where('state', 0)->exists();
                    if ($isExists) {
//                        WxShopCart::where('user_id', $uid)->where('product_id', $pid)
//                            ->increment('num', (int)$num);
                    } else {
                        $model = new WxShopCart();
                        $model->user_id = $uid;
                        $model->seller_user_id = $shop_goods->user_id;
                        $model->goods_id = $goods_id;
                        $model->product_id = $pid;
                        $model->goods_pic = $WxShopGoodsProduct->pic;
                        $model->goods_name = $shop_goods->name;
                        $model->goods_product = $WxShopGoodsProduct->param_value;
                        $model->price = $WxShopGoodsProduct->price;
                        $model->vip_price = $WxShopGoodsProduct->vip_price;
                        $model->credit_type = $WxShopGoodsProduct->credit_type;
                        $model->goods_type = $shop_goods->type;
                        $model->num = $num;
                        $model->is_check = 1;
                        $model->save();
                    }
//                    WxShopGoodsProduct::where('id', $pid)->update(['stock' => $pstock - $num]);//减库存
                    UserUtils::add_user_experience($uid, 10);
                    return $this->success();
                }else if($action == 'buy' || $action == 'gold'){

                    $model = new WxShopCart();
                    $model->user_id = $uid;
                    $model->seller_user_id = $shop_goods->user_id;
                    $model->goods_id = $goods_id;
                    $model->product_id = $pid;
                    $model->goods_pic = $WxShopGoodsProduct->pic;
                    $model->goods_name = $shop_goods->name;
                    $model->goods_product = $WxShopGoodsProduct->param_value;
                    $model->price = $WxShopGoodsProduct->price;
                    $model->vip_price = $WxShopGoodsProduct->vip_price;
                    $model->credit_type = $WxShopGoodsProduct->credit_type;
                    $model->num = $num;
                    $model->goods_type = $shop_goods->type;
                    $model->is_check = 1;
                    $model->state = $action == 'buy' ? 4 : 5;
                    $model->save();
//                    WxShopGoodsProduct::where('id', $pid)->update(['stock' => $pstock - $num]);//减库存
                    UserUtils::add_user_experience($uid, 10);
                    return $this->success(['cart_id' => $model->id]);
                }

            } else {
                return $this->fail(800001);
            }
        }
    }




    /**
     * Shop用户购物袋列表
     */
    public function userCartList(Request $request)
    {
        $uid = $request->uid;

        $pIds = WxShopCart::where('user_id', $uid)->pluck('product_id');//购物袋规格ID列表

        foreach ($pIds as $v) {
            $isExists = WxShopGoodsProduct::where('id', $v)->where('state', 0)->exists();
            if (!$isExists) {
                WxShopCart::where('user_id', $uid)->where('product_id', $v)->where('state', 0)
                    ->update(['state' => 3]);
            }
        }

        $shop_state_0_goods = WxShopGoods::whereIn('id', WxShopCart::where('user_id', $uid)->pluck('goods_id')->toArray())->where('state', 0)->pluck('id');
        foreach ($shop_state_0_goods as $good_0_id){
            WxShopCart::where('user_id', $uid)->where('goods_id', $good_0_id)->where('state', 0)
                ->update(['state' => 3]);
        }

        $data = WxShopCart::where('user_id', $uid)
            ->whereIn('state', [0,3])
            ->orderBy('created_at', 'desc')
            ->get()->map(function ($v){
                if(_empty_($v->num)){
                    $v->num = 1;
                }
                return $v;
            });

        return $this->success($data);
    }

    /**
     * Shop修改购物袋商品数量
     */
    public function saveCartNum(Request $request)
    {
        $uid = $request->uid;
        $pid = $request->pid;
        $num = $request->num;

        if(_empty_($num) || $num <= 0 || _empty_($pid)){
            return $this->fail(200001);
        }

        $stock = WxShopGoodsProduct::where('id', $pid)->value('stock');
        $cnum = WxShopCart::where('user_id', $uid)->where('product_id', $pid)->where('state', 0)->value('num');

        if ($stock > $num - $cnum) {
            WxShopCart::where('user_id', $uid)->where('product_id', $pid)->where('state', 0)
                ->update(['num' => $num]);

            $pstock = $stock - ($num - $cnum);
            WxShopGoodsProduct::where('id', $pid)->update(['stock' => $pstock]);//减库存
            return $this->success();
        } else {
            return $this->fail(800002, $stock);
        }
    }

    /**
     * Shop选中购物袋商品
     */
    public function checkCartGoods(Request $request)
    {
        $uid = $request->uid;
        $pid = $request->pid;
        $check = $request->check;

        WxShopCart::where('user_id', $uid)->where('product_id', $pid)->where('state', 0)
            ->update(['is_check' => $check]);

        return $this->success();
    }

    /**
     * Shop全选购物袋商品
     */
    public function allCheckCartGoods(Request $request)
    {
        $uid = $request->uid;
        $is_check = $request->is_check;

        WxShopCart::where('user_id', $uid)->where('state', 0)
            ->update(['is_check' => $is_check]);

        return $this->success();
    }

    /**
     * Shop删除购物袋商品
     */
    public function delCartGoods(Request $request)
    {
        $cid = $request->cid;

        if(_empty_($cid)){
            return $this->fail(200001);
        }

        WxShopCart::where('id', $cid)
            ->update(['state' => 1]);

        return $this->success();
    }


    /**
     * Shop用户默认地址
     */
    public function getCheckAdds(Request $request)
    {
        $uid = $request->uid;
        $aid = $request->aid;

        if ($aid == -1) {
            $data = WxShopAddress::where('user_id', $uid)->where('is_check', 1)->where('state', 0)->first();
        } else {
            $data = WxShopAddress::where('user_id', $uid)->where('id', $aid)->where('state', 0)->first();
        }

        return $this->success($data);
    }

    /**
     * Shop用户地址列表
     */
    public function getAddsList(Request $request)
    {
        $uid = $request->uid;

        $data = WxShopAddress::where('user_id', $uid)->where('state', 0)
            ->orderBy('is_check', 'desc')
            ->orderBy('created_at', 'desc')->get();

        return $this->success($data);
    }

    /**
     * Shop增加/修改地址
     */
    public function saveAdds(Request $request)
    {
        $uid = $request->uid;
        $aid = $request->aid;
        $name = $request->name;
        $mobile = $request->mobile;
        $province = $request->province;
        $city = $request->city;
        $county = $request->county;
        $adds = $request->adds;
        $is_check = $request->is_check;
        if ($is_check == 1) {
            WxShopAddress::where('user_id', $uid)->where('is_check', 1)->where('state', 0)->update(['is_check' => 0]);
        }

        if ($aid == -1) {
            $model = new WxShopAddress();
            $model->user_id = $uid;
            $model->name = $name;
            $model->mobile = $mobile;
            $model->province = $province;
            $model->city = $city;
            $model->county = $county;
            $model->adds = $adds;
            $model->is_check = $is_check;
            $model->save();
        } else {
            WxShopAddress::where('user_id', $uid)->where('id', $aid)->where('state', 0)
                ->update(['name' => $name,
                    'mobile' => $mobile,
                    'province' => $province,
                    'city' => $city,
                    'county' => $county,
                    'adds' => $adds,
                    'is_check' => $is_check]);
        }

        return $this->success();
    }

    /**
     * Shop用户删除地址
     */
    public function delAdds(Request $request)
    {
        $uid = $request->uid;
        $aid = $request->aid;

        $data = WxShopAddress::where('user_id', $uid)->where('id', $aid)->where('state', 0)
            ->update(['state' => 1]);

        return $this->success($data);
    }

    /**
     * Shop订单修改地址
     */
    public function orderAddress(Request $request){
        $order_id = $request->order_id;
        $aid = $request->aid;
        $uid = $request->uid;

        if(_empty_($order_id) || _empty_($aid)){
            return $this->fail(200001);
        }

        $order_id = _abs($order_id);
        $aid = _abs($aid);

        $shop_order = WxShopOrder::where('id', $order_id)->where('user_id', $uid)->where('status', 1)->first();
        if(!$shop_order){
            return $this->fail(200003);
        }

        $address = WxShopAddress::where('id', $aid)->where('user_id', $uid)->where('state', 0)->first();
        if(!$address){
            return $this->fail(200003);
        }

        $shop_order->adds_id = $address->id;
        $shop_order->adds_name = $address->name;
        $shop_order->adds_mobile = $address->mobile;
        $shop_order->address = $address->province . $address->city . $address->county . $address->adds;
        $r = $shop_order->save();
        if($r){
            return $this->success(['adds_id'=>$shop_order->adds_id,
                'adds_name'=>$shop_order->adds_name,
                'adds_mobile'=>$shop_order->adds_mobile, 'address'=>$shop_order->address]);
        }else{
            return $this->fail(200002);
        }
    }

    /**
     * Shop下单商品列表
     */
    public function pliceOrderGoods(Request $request)
    {
        $uid = $request->uid;
        $cart_id = $request->cart_id;

        if(_empty_($cart_id)){
            $cart_id = 0;
        }

        if($cart_id > 0){
            // 4: 人民币 5：金币
            $data = WxShopCart::where('id', $cart_id)
                ->get(['id', 'goods_id', 'goods_type', 'goods_name', 'goods_pic', 'goods_product', 'num', 'price', 'product_id', 'vip_price', 'credit_type']);
        }else{
            $data = WxShopCart::where('user_id', $uid)->where('is_check', 1)
                ->where('state', 0)
                ->get(['id', 'goods_id', 'goods_type', 'goods_name', 'goods_pic', 'goods_product', 'num', 'price', 'product_id', 'vip_price', 'credit_type']);
        }

        return $this->success($data);
    }

	/**
     * Shop用户购物袋数量
     */
    public function userCartCount(Request $request)
    {
        $uid = $request->uid;
        return $this->success(ShopUtils::user_cart_count($uid));
    }

    /**
     * 解析淘客商品
     */
    public function taokeParseUrl(Request $request){
        $url = $request->url;
        if(_empty_($url)){
            return $this->fail(200001);
        }

        global $__MINI_GLOBAL_PAYCODE_13__;
        if(!$__MINI_GLOBAL_PAYCODE_13__){
            return $this->fail(700000);
        }

        $res = preg_match('$item\.m\.jd\.com/product/(\d+)\.html$', $url, $matchs);
        if($res <= 0){
            $res = preg_match('$item\.jd\.com/(\d+)\.html$', $url, $matchs);
        }
        if($res > 0){
            if($matchs[1] > 0){
                $goods_id_obj = TaokeUtils::get_goods_id_from_taoke(0, $matchs[1], 3);
                if($goods_id_obj && $goods_id_obj['code'] == 1){
                    $goods = WxShopGoods::find($goods_id_obj['data']);
                    return $this->success(['id'=>$goods_id_obj['data'], 'name'=>$goods->name, 'pic'=>_array_key($goods->pic, 0, '')]);
                }else{
                    _logger_(__file__, __line__, $url);
                    return $this->fail(200006, [], '解析失败，请等会再重试_jd');
                }
            }
        }else{
            if(preg_match('$haohuo\.jinritemai\.com$', $url) > 0 || preg_match('$v\.douyin\.com$', $url) > 0){
                // 抖音
                if(preg_match('$haohuo\.jinritemai\.com$', $url) > 0){
                    $res = preg_match('$[\?&]id=(\d+)$', $url, $matchs);
                    if($res > 0){
                        if($matchs[1] > 0){
                            $goods_id_obj = TaokeUtils::get_goods_id_from_taoke(0, $matchs[1], 5);
                            if($goods_id_obj && $goods_id_obj['code'] == 1){
                                $goods = WxShopGoods::find($goods_id_obj['data']);
                                return $this->success(['id'=>$goods_id_obj['data'], 'name'=>$goods->name, 'pic'=>_array_key($goods->pic, 0, '')]);
                            }else{
                                return $this->fail(200006, [], '解析失败，请等会再重试_dy1');
                            }
                        }
                    }else{
                        _logger_(__file__, __line__, $url);
                        return $this->fail(200006, [], '解析失败，请等会再重试_dy2');
                    }
                }else{
                    return $this->fail(200004, [], '不支持抖音短链接，请把短连接放到浏览器，然后复制长链接进行尝试');
                }
            }else{
                if(preg_match('$yangkeduo\.com$', $url) > 0){
                    $res = preg_match('$[\?&]goods_id=(\d+)$', $url, $matchs);
                    if($res > 0){
                        if($matchs[1] > 0){
                            $goods_id_obj = TaokeUtils::get_goods_id_from_taoke(0, $matchs[1], 4);
                            if($goods_id_obj && $goods_id_obj['code'] == 1){
                                $goods = WxShopGoods::find($goods_id_obj['data']);
                                return $this->success(['id'=>$goods_id_obj['data'], 'name'=>$goods->name, 'pic'=>_array_key($goods->pic, 0, '')]);
                            }else{
                                _logger_(__file__, __line__, $url);
                                return $this->fail(200006, [], '解析失败，请等会再重试_pdd');
                            }
                        }
                    }else{
                        _logger_(__file__, __line__, $url);
                        return $this->fail(200006, [], '解析失败，请等会再重试_pdd');
                    }
                }else{
                    // 剪切版识别
                    $res = TaokeUtils::get_taobao_item_from_content($url);
                    if($res['code'] == 1){

                    }else{
                        // 淘口令解析
                        $res = TaokeUtils::get_taobao_item_from_taokouling($url);
                        if($res['code'] == 1){

                        }else{
                            return $this->fail(200006, [], '解析失败，暂时只支持淘宝，京东，拼多多，抖音的商品链接！_tb');
                        }
                    }

                    $goods_id_obj = TaokeUtils::get_goods_id_from_taoke(0, $res['data'], 1);
                    if($goods_id_obj && $goods_id_obj['code'] == 1){
                        $goods = WxShopGoods::find($goods_id_obj['data']);
                        return $this->success(['id'=>$goods_id_obj['data'], 'name'=>$goods->name, 'pic'=>_array_key($goods->pic, 0, '')]);
                    }else{
                        _logger_(__file__, __line__, $url);
                        return $this->fail(200006, [], '解析失败，请等会再重试_tb');
                    }

                }
            }

        }

    }

}
